package com.flyfox.ffplayer.util;

import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.flyfox.ffplayer.model.FFPlayer;
import com.flyfox.ffplayer.model.MusicType;

import javafx.collections.MapChangeListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

/**
 * 公共方法
 * 
 * @author flyfox
 * @date 2014年11月7日
 */
public class FFPlayerUtils {

	public final static AtomicBoolean CLOSE = new AtomicBoolean(true);
	
	private static AtomicLong genID = new AtomicLong();

	/**
	 * 获取FFPlayer信息，进行初始化
	 * 
	 * @param path
	 * @return
	 */
	public static FFPlayer getFFPlayer(String path) {
		String music = path.substring(path.lastIndexOf(File.separatorChar) + 1);
		MediaPlayer mediaPlayer = FFPlayerUtils.getMediaPlayer(path);
		FFPlayer model = new FFPlayer();
		// 全路径
		model.setPath(path);
		// 唯一ID
		model.setId(genID.getAndIncrement() + "");
		model.setMediaPlayer(mediaPlayer);
		String name = music.substring(0, music.lastIndexOf("."));
		model.setFileName(name);
		String type = music.substring(music.lastIndexOf(".") + 1);
		MusicType musicType = MusicType.valueOf(type.toUpperCase());
		if (musicType == null) {
			model.setType(MusicType.MP3);
		} else {
			model.setType(musicType);
		}

		/**
		 * album artist：專輯演出者。 album：專輯名稱。 artist：演出者。 composer：作曲者。
		 * comment-N：專輯第N首音軌的註解。 disc count：專輯光碟數目。 disc number：專輯光碟編號。
		 * duration：音軌時間長度。 genre：音軌類型如流行樂、搖滾樂等。 image：專輯封面。 title：音軌名稱。 track
		 * count：音軌總數。 track number：音軌編號。 year：專輯年份。
		 */
		mediaPlayer.getMedia().getMetadata().addListener(new MapChangeListener<String, Object>() {
			@Override
			public void onChanged(MapChangeListener.Change<? extends String, ? extends Object> change) {

				if (change.wasAdded()) {
					String key = change.getKey();
					Object value = change.getValueAdded();
					if (key.equals("album")) {
						// 专辑
						if (!FFPlayerUtils.isMessyCode(value.toString())) {
							model.setAlbum(value.toString());
						}
					} else if (key.equals("artist")) {
						// 作者
						if (!FFPlayerUtils.isMessyCode(value.toString())) {
							model.setArtist(value.toString());
						}
					} else if (key.equals("duration")) {
						// 时间
						model.setTotleTime((Duration) value);// UNKNOWN
					} else if (key.equals("title")) {
						// 名称，乱码就算了吧
						if (!FFPlayerUtils.isMessyCode(value.toString())) {
							model.setTitle(value.toString());
						}

					}
				}
			}
		});
		mediaPlayer.getMedia().getMetadata().forEach((action, b) -> {
			System.out.println(action.toString() + ":" + b.toString());
		});
		// 如果文件没有获取到MP3题目，取文件名
		if (model.getTitle() == null) {
			model.setTitle(name);
		}
		return model;
	}

	public static MediaPlayer getMediaPlayer(String filePath) {
		File file = new File(filePath);
		Media media = new Media(file.toURI().toString());
		MediaPlayer mediaPlayer = new MediaPlayer(media);
		return mediaPlayer;
	}

	/**
	 * 判断字符是否是中文
	 *
	 * @param c
	 *            字符
	 * @return 是否是中文
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断字符串是否是乱码
	 *
	 * @param strName
	 *            字符串
	 * @return 是否是乱码
	 */
	public static boolean isMessyCode(String strName) {
		if (strName == null) {
			return false;
		}

		Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
		Matcher m = p.matcher(strName);
		String after = m.replaceAll("");
		String temp = after.replaceAll("\\p{P}", "");
		char[] ch = temp.trim().toCharArray();
		float chLength = ch.length;
		float count = 0;
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (!Character.isLetterOrDigit(c)) {
				if (!isChinese(c)) {
					count = count + 1;
				}
			}
		}
		float result = count / chLength;
		if (result > 0.4) {
			return true;
		} else {
			return false;
		}

	}

}
